package com.ll.gulimall.ware.service.impl;

import com.ll.common.constant.WareConstant;
import com.ll.gulimall.ware.entity.PurchaseDetailEntity;
import com.ll.gulimall.ware.service.PurchaseDetailService;
import com.ll.gulimall.ware.service.WareSkuService;
import com.ll.gulimall.ware.vo.MergeVo;
import com.ll.gulimall.ware.vo.PurchaseDoneVo;
import com.ll.gulimall.ware.vo.PurchaseItems;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ll.common.utils.PageUtils;
import com.ll.common.utils.Query;

import com.ll.gulimall.ware.dao.PurchaseDao;
import com.ll.gulimall.ware.entity.PurchaseEntity;
import com.ll.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils unreceiveList(Map<String, Object> params) {

        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper.eq("status", WareConstant.WarePurchaseEnum.CREATED.getCode()).or().eq("status", WareConstant.WarePurchaseEnum.ASSIGNED.getCode())
        );

        return new PageUtils(page);


    }

    @Autowired
    PurchaseDetailService purchaseDetailService;

    @Autowired
    WareSkuService wareSkuService;

    @Transactional
    @Override
    public void merge(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        if (purchaseId == null) {
            //则没有选择合并的采购单 则创建
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setPriority(0);
            purchaseEntity.setUpdateTime(new Date());

            purchaseEntity.setStatus(WareConstant.WarePurchaseEnum.ASSIGNED.getCode());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }

        //开始合并  需要合并的采购需求Id
        List<Long> items = mergeVo.getItems();
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> collect = items.stream().map(i -> {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            detailEntity.setId(i);
            detailEntity.setPurchaseId(finalPurchaseId);
            detailEntity.setStatus(WareConstant.PurchaseDatailStatusEnum.ASSIGNED.getCode());
            return detailEntity;
        }).filter(item -> {
            if (item.getStatus() == WareConstant.PurchaseDatailStatusEnum.CREATED.getCode() || item.getStatus() == WareConstant.PurchaseDatailStatusEnum.ASSIGNED.getCode()) {
                return true;
            }
            return false;
        }).collect(Collectors.toList());
        //合并就是修改采购需求的采购单Id
        purchaseDetailService.updateBatchById(collect);
        //修改采购单的修改日期
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }


    /**
     * 领取采购单
     *
     * @param ids
     */
    @Override
    @Transactional
    public void received(List<Long> ids) {
        //获取需要领取的采购单
        List<PurchaseEntity> purchaseEntityList = ids.stream().map(
                item -> {
                    PurchaseEntity byId = this.getById(item);
                    byId.setUpdateTime(new Date());//修改时间
                    return byId;
                }
        ).filter(item -> {
            //过滤掉不能被领取的采购单
            if (item.getStatus() == WareConstant.WarePurchaseEnum.CREATED.getCode() || item.getStatus() == WareConstant.WarePurchaseEnum.ASSIGNED.getCode()) {
                //给能领取的采购单设置新的状态
                item.setStatus(WareConstant.WarePurchaseEnum.RECEIVE.getCode());
                return true;
            }
            return false;
        }).collect(Collectors.toList());
        //改变采购单状态
        this.updateBatchById(purchaseEntityList);
        //改变采购信息表状态
        purchaseEntityList.forEach(purchaseEntity -> {
            //查询采购需求
            List<PurchaseDetailEntity> datilList = purchaseDetailService.listDatilByPurchaseId(purchaseEntity.getId());
            List<PurchaseDetailEntity> collect = datilList.stream().map(datil -> {
                PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
                detailEntity.setId(datil.getId());
                detailEntity.setStatus(WareConstant.PurchaseDatailStatusEnum.BUYING.getCode());
                return detailEntity;
            }).collect(Collectors.toList());
            //根据采购单的Id改变采购需求的状态
            purchaseDetailService.updateBatchById(collect);

        });

    }


    @Transactional
    @Override
    public void done(PurchaseDoneVo purchaseDoneVo) {
        //采购项是否有采购失败的 如果有采购单则是有异常状态
        Boolean flag = true;
        // 2.修改采购项状态
        List<PurchaseItems> items = purchaseDoneVo.getItems();
        for (PurchaseItems item : items) {
            //改变采购项状态
            PurchaseDetailEntity detailEntity = purchaseDetailService.getById(item.getItemId());
            detailEntity.setStatus(item.getStatus());
            purchaseDetailService.updateById(detailEntity);
            if (item.getStatus() == WareConstant.PurchaseDatailStatusEnum.HASERROR.getCode()) {
                flag = false;
            } else {
                //如果采购成功则改变库存
                // 3.添加到库存
                wareSkuService.addStock(detailEntity.getSkuId(), detailEntity.getWareId(), detailEntity.getSkuNum());
            }
        }
        // 1.修改采购单状态
        //采购单Id
        Long id = purchaseDoneVo.getId();
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setUpdateTime(new Date());
        //如果所有采购项都成功了则 成功 否则失败
        if (!flag) {
            purchaseEntity.setStatus(WareConstant.WarePurchaseEnum.HASERROR.getCode());
        } else {
            purchaseEntity.setStatus(WareConstant.WarePurchaseEnum.FINISH.getCode());
        }
        this.updateById(purchaseEntity);
    }

}